package com.shiyingzi.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.shiyingzi.common.Constants;

public class FileUtil {

	public static boolean uploadFile(String fileNewName, String dir, MultipartFile file) {
		boolean bool = true;
		try {
			File ffile=new File(dir);
			if(!ffile.exists()&&!ffile.isDirectory()){
				ffile.mkdirs();
			}
			InputStream fis=file.getInputStream();
			OutputStream fos=new FileOutputStream(dir+fileNewName);
			int c=0;
			byte[] buff=new byte[1024];
			while((c=fis.read(buff,0,1024))!=-1){
				fos.write(buff,0,c);
			}
			fos.close();
		} catch (Exception e) {
			bool = false;
		}
		return bool;
	}
	
	public static void fileChannelCopy(String filePath, String fileName,MultipartFile file) {
		File fileCopy=new File(filePath);
		if(!fileCopy.exists()&&!fileCopy.isDirectory()){
			fileCopy.mkdirs();
		}
		File newFile =new File(filePath+System.getProperties()
				.getProperty("file.separator")+fileName);
        FileInputStream fi = null;

        FileOutputStream fo = null;

        FileChannel in = null;

        FileChannel out = null;

        try {

            fi =(FileInputStream)file.getInputStream();

            fo = new FileOutputStream(newFile);

            in = fi.getChannel();

            out = fo.getChannel();

            in.transferTo(0, in.size(), out);

        } catch (IOException e) {

            e.printStackTrace();

        } finally {

            try {

                fi.close();

                in.close();

                fo.close();

                out.close();

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

    }
	
	public static void download(HttpServletRequest request,
                                HttpServletResponse response, String uploadPath, String attachName, String fileName) {
    	BufferedInputStream bis = null;  
        BufferedOutputStream bos = null;  
        String path = "/";
		if(System.getProperty("os.name").indexOf("Windows") > -1){
			path = "D:/";
		}
        //闂勫嫪娆RL閸︽澘娼�
        String downLoadPath = path + uploadPath + attachName; 
        String showName = fileName + attachName;
        try {
        	File file = new File(downLoadPath);
	        response.reset();
	        response.setContentType("application/octet-stream");  
	        response.setHeader("Content-disposition", "attachment; filename=" + new String(showName.getBytes()));
	        response.setHeader("Content-Length", String.valueOf(file.length()));
        
            bis = new BufferedInputStream(new FileInputStream(downLoadPath));  
            bos = new BufferedOutputStream(response.getOutputStream());  
            byte[] buff = new byte[2048];  
            int bytesRead;  
            while ((bytesRead = bis.read(buff, 0, buff.length)) > 0) {  
                bos.write(buff, 0, bytesRead);  
            } 
            bos.flush();
		} catch (Exception e) {
		}finally{
			if(bis != null){
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(bos != null){
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
    }
	 
	public static void downloadFile(String path, HttpServletResponse response) throws Exception {
		
		File file = new File(path);
		
		String filename = file.getName();
		
		InputStream fis = new BufferedInputStream(new FileInputStream(path));
		byte[] buffer = new byte[fis.available()];
		fis.read(buffer);
		fis.close();
		
		response.reset();
		
		response.addHeader("Content-Disposition", "attachment;filename="
				+ new String(filename.getBytes()));
		response.addHeader("Content-Length", "" + file.length());
		OutputStream toClient = new BufferedOutputStream(
				response.getOutputStream());
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		toClient.write(buffer);
		toClient.flush();
		toClient.close();
	}
	/**
	 * 上传头像图片
	 * @param file
	 * @return 
	 * @param file图片文件
	 * @param newName 图片名称
	 * @param saveFilePath 实际保存路径
	 * @return map：   flag判断真假  为假：  message错误提示   为真：urldatepath图片地址一般为传入的newName
	 * @throws ServletException
	 * @throws IOException
	 * @throws ParseException
	 */
	public static Map<String, Object> uploadimg(MultipartFile file,String newName
			,String saveFilePath) throws ServletException, IOException, ParseException {
		Map<String, Object> map = new HashMap<String, Object>();
		String oldName=file.getOriginalFilename();
		   String suffix=oldName.substring(oldName.lastIndexOf("."));
		   if (!suffix.equals(".JPG") &&!suffix.equals(".GIF") &&!suffix.equals(".PNG") &&!suffix.equals(".SWF") &&!suffix.equals(".JPEG") &&
					!suffix.equals(".jpg") && !suffix.equals(".gif") && !suffix.equals(".png") && !suffix.equals(".swf")&& !suffix.equals(".jpeg")){
			   map.put("message", "文件上传应为图片");
			   map.put("flag", false);
			   return map;
		   }
		   if (file.getSize() > 20971520) {
			   map.put("message", "上传图片不能大于20M");
			   map.put("flag", false);
			   return map;
			}
		   if(newName==null || newName.equals("")){
			   SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			    String datetime=sdf.format(new Date()); 
			     newName=oldName.substring(0,oldName.indexOf("."));
			    newName=newName.replace(" ", "");
			   newName=datetime+"_"+newName+oldName.substring(oldName.lastIndexOf("."));
			   
		   }
		    if(saveFilePath==null || saveFilePath.equals("")){
		    	  saveFilePath=Constants.BOOK_IMG_PATH;
		    }
		    //存入数据库的图片地址
//		   String urldatepath=newName;
		    String urldatepath=saveFilePath+"\\"+newName;
//		    System.out.println("saveFilePath的路径是："+saveFilePath+"\\"+newName);
//		    System.out.println("urldatepath的路径是："+urldatepath);
		    /* 构建文件目录 */
		    File fileDir = new File(saveFilePath);
		    if (!fileDir.exists()) {
		        fileDir.mkdirs();
		    }
	        FileOutputStream out = null;
		    try {
		    	   out = new FileOutputStream(saveFilePath+"\\"+newName);
		    //			   + "\\"+newName);     //从本地文件
		        // 写入文件
		        out.write(file.getBytes());
		        out.flush();
		        out.close();
		    } catch (Exception e) {
		      map.put("message", "文件上传错误");
		      map.put("flag", false);
		      return map;
		    }
		    map.put("urldatepath", urldatepath);
		    map.put("flag", true);
		    return map;
	}
	
	public static String MD5(String sourceStr) {
        String result = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(sourceStr.getBytes());
            byte b[] = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            result = buf.toString();
        } catch (NoSuchAlgorithmException e) {
            System.out.println(e);
        }
        return result;
    }
}
